package oa.util;

import oa.bean.TUser;
import oa.shiro.RedisRealm;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.mgt.RealmSecurityManager;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.BeanUtils;

public class ShiroUtil {
	
    public static Subject getSubject()
    {
        return SecurityUtils.getSubject();
    }

    public static Session getSession()
    {
        return SecurityUtils.getSubject().getSession();
    }

    public static void logout()
    {
    	SecurityUtils.getSubject().logout();
    }

    public static Object getPrincipal() {
    	return SecurityUtils.getSubject().getPrincipal();
    }
    
    public static TUser getUser()
    {
        TUser user = new TUser();
        BeanUtils.copyProperties(SecurityUtils.getSubject().getPrincipal(), user);
        return user;
    }

    public static void setUser(TUser user)
    {
        Subject subject = getSubject();
        PrincipalCollection principalCollection = subject.getPrincipals();
        String realmName = principalCollection.getRealmNames().iterator().next();
        PrincipalCollection newPrincipalCollection = new SimplePrincipalCollection(user, realmName);
        // 重新加载Principal
        subject.runAs(newPrincipalCollection);
    }

    public static void clearCachedAuthorizationInfo()
    {
        RealmSecurityManager rsm = (RealmSecurityManager) SecurityUtils.getSecurityManager();
        RedisRealm realm = (RedisRealm) rsm.getRealms().iterator().next();
        realm.clearCachedAuthorizationInfo();
    }
}
